package com.xb.loan.cashier.biz.pay.bankcomm.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class BankcommSubmit {
	
	private static Logger log = LoggerFactory.getLogger(BankcommSubmit.class);

	/**
	 * 使用java实现模拟往交行API地址post报文
	 * @param httpsType
	 * @param url
	 * @param param
	 * @return
	 */
	public static String post(String httpsType, String url, String param) {
		String response = "";
		try {
			//信任自签名https证书，仅允许用于测试环境
			if(httpsType.equals("httpsTrustAllCerts")){
				log.debug("信任自签名https证书，用于测试环境忽略所有https证书错误，严禁在生产环境使用本段代码");
				javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[] { new javax.net.ssl.X509TrustManager() {
					public java.security.cert.X509Certificate[] getAcceptedIssuers() {return null;}
					public void checkClientTrusted(java.security.cert.X509Certificate[] certs,String authType) {}
					public void checkServerTrusted(java.security.cert.X509Certificate[] certs,String authType) {}
				} };
				javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("TLS");
				sc.init(null, trustAllCerts, null);
				javax.net.ssl.SSLSocketFactory ssf = sc.getSocketFactory();
				//以上代码用于测试环境忽略所有https证书错误，严禁在生产环境使用本段代码
				javax.net.ssl.HttpsURLConnection conn = (javax.net.ssl.HttpsURLConnection) new java.net.URL(url).openConnection();
				conn.setSSLSocketFactory(ssf);// 测试环境尝试忽略所有https证书错误，严禁在生产环境使用本段代码
				conn.setRequestMethod("POST");
				conn.setDoOutput(true);// 是否输入参数
				java.io.OutputStream outStream = conn.getOutputStream();
				outStream.write(param.getBytes("GBK"));// 输入参数
				outStream.close();
				java.io.InputStream inStream = conn.getInputStream();
				java.io.ByteArrayOutputStream byteArray = new  java.io.ByteArrayOutputStream();
				int byteData = 0;
				while ((byteData = inStream.read()) != -1) {
					byteArray.write(byteData);
				}
				inStream.close();
				byte[] bytes = byteArray.toByteArray();
				byteArray.close();
				response = new String(bytes, "GBK");
			}
			//使用https协议请求交行API地址，用于生产环境
			else if(httpsType.equals("https")){
				javax.net.ssl.HttpsURLConnection conn = (javax.net.ssl.HttpsURLConnection) new java.net.URL(url).openConnection();
				conn.setRequestMethod("POST");
				conn.setDoOutput(true);// 是否输入参数
				java.io.OutputStream outStream = conn.getOutputStream();
				outStream.write(param.getBytes("GBK"));// 输入参数
				outStream.close();
				java.io.InputStream inStream = conn.getInputStream();
				java.io.ByteArrayOutputStream byteArray = new  java.io.ByteArrayOutputStream();
				int byteData = 0;
				while ((byteData = inStream.read()) != -1) {
					byteArray.write(byteData);
				}
				inStream.close();
				byte[] bytes = byteArray.toByteArray();
				byteArray.close();
				response = new String(bytes, "GBK");
			}
			//使用http协议请求交行API地址，可用于专线环境
			else if(httpsType.equals("http")){
				java.net.HttpURLConnection conn = (java.net.HttpURLConnection) new java.net.URL(url).openConnection();
				conn.setRequestMethod("POST");
				conn.setDoOutput(true);// 是否输入参数
				java.io.OutputStream outStream = conn.getOutputStream();
				outStream.write(param.getBytes("GBK"));// 输入参数
				outStream.close();
				java.io.InputStream inStream = conn.getInputStream();
				java.io.ByteArrayOutputStream byteArray = new  java.io.ByteArrayOutputStream();
				int byteData = 0;
				while ((byteData = inStream.read()) != -1) {
					byteArray.write(byteData);
				}
				inStream.close();
				byte[] bytes = byteArray.toByteArray();
				byteArray.close();
				response = new String(bytes, "GBK");
			}
		} catch (Exception e) {
			log.error("后台POST报文失败",e);
		}
		return response;
	}
	
	/**
	 * 功能：前台交易构造HTTP POST自动提交表单<br>
	 * @param reqUrl 表单提交地址<br>
	 * @param hiddens 以MAP形式存储的表单键值<br>
	 * @param encoding 上送请求报文域encoding字段的值<br>
	 * @return 构造好的HTTP POST交易表单<br>
	 */
	public static String createAutoFormHtml(String reqUrl, Map<String, String> hiddens, String encoding) {
		StringBuffer sf = new StringBuffer();
		sf.append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset="+encoding+"\"/></head><body>");
		sf.append("<form id = \"pay_form\" action=\"" + reqUrl
				+ "\" method=\"post\">");
		if (null != hiddens && 0 != hiddens.size()) {
			Set<Entry<String, String>> set = hiddens.entrySet();
			Iterator<Entry<String, String>> it = set.iterator();
			while (it.hasNext()) {
				Entry<String, String> ey = it.next();
				String key = ey.getKey();
				String value = ey.getValue();
				sf.append("<input type=\"hidden\" name=\"" + key + "\" id=\""
						+ key + "\" value=\"" + value + "\"/>");
			}
		}
		sf.append("</form>");
		sf.append("</body>");
		sf.append("<script type=\"text/javascript\">");
		sf.append("document.all.pay_form.submit();");
		sf.append("</script>");
		sf.append("</html>");
		log.debug("createAutoFormHtml html="+sf.toString());
		return sf.toString();
	}


}
